package com.artmall.manager.sys.service.impl;

import com.artmall.common.utils.R;
import com.artmall.common.utils.ShiroUtils;
import com.artmall.common.utils.StringUtil;
import com.artmall.manager.sys.dao.SysUserMapper;
import com.artmall.manager.sys.pojo.SysUser;
import com.artmall.manager.sys.service.SysUserService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: MING
 * @Eamil lmm_work@163.com
 * @Date: 2018/11/22 12:07
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper,SysUser> implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Override
    public SysUser getUserById(Long id) {
        return sysUserMapper.selectById(id);
    }

/*
     PageHelper 分页

     PageHelper.startPage(pageNo,pageSize);
     List<SysUser> sysUserList = sysUserMapper.selectAll();
     PageInfo<SysUser> pageInfo = new PageInfo<>(sysUserList);
 */

    @Override
    public R getAllUser(Integer pageNo,Integer pageSize,String searchKey,String searchValue) {

        EntityWrapper<SysUser> wrapper = new EntityWrapper<>();
        if(StringUtil.isNotBlank(searchKey)){
            wrapper.like(searchKey,searchValue);
        }
        Page<SysUser> page = new Page<>(pageNo,pageSize);
        List<SysUser> sysUserList = sysUserMapper.selectPage(page, wrapper);
        return R.ok().put("count",page.getTotal()).put("data",sysUserList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUser sysUser) {
        sysUser.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        sysUser.setSalt(salt);
        sysUser.setPassword(ShiroUtils.sha256(sysUser.getPassword(),salt));
        this.insert(sysUser);

        // 保存用户角色关系
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUser sysUser) {
     /*   if (StringUtil.isNotBlank(sysUser.getPassword())){
            sysUser.setPassword(null);
        }else{
            sysUser.setPassword(ShiroUtils.sha256(sysUser.getPassword(),sysUser.getSalt()));
        }*/
        sysUser.setUpdateTime(new Date());
        this.updateById(sysUser);

        // 保存用户角色关系
    }

    @Override
    public SysUser selectOne(SysUser sysUser) {
        SysUser user = sysUserMapper.selectOne(sysUser);
        return user;
    }

    @Override
    public List<String> queryAllPerms(Long userId) {
        return sysUserMapper.queryAllPerms(userId);
    }


}
